//
//  AppStats.m
//  navigation
//
//  Created by ppcfan on 10-9-9.
//

#import "AppStats.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"

@implementation AppStats

//-(id) initWithAppId:(NSString*)_id Version:(NSString*)_version Delegate:(id)_delegate;
-(id) initWithDelegate:(id)_delegate
{
	self = [super init];
	
	if (self)
	{
		m_appId = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"] retain];
		m_appVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] retain];
		m_locale = [[[NSLocale currentLocale] localeIdentifier] retain];
		m_deviceId = [[UIDevice currentDevice] uniqueIdentifier];
		m_deviceType = [[UIDevice currentDevice] model];
		m_deviceVersion = [[UIDevice currentDevice] systemVersion];
	
		m_delegate = [_delegate retain];
		
		m_receivedData = [[NSMutableData data] retain];
	}
	
	return self;
}

-(void) dealloc
{	
	[m_appId release];
	[m_appVersion release];
	[m_locale release];
	[m_deviceId release];
	[m_deviceType release];
	[m_deviceVersion release];
	
	[m_delegate release];
	
	[m_receivedData release];
	[super dealloc];
}

-(BOOL) requestNotification
{
	[m_receivedData setLength:0];
	
	NSDictionary* commandDict = [NSDictionary dictionaryWithObjectsAndKeys:
							   API_VERSION, @"statsVersion", nil];
	
	NSDictionary* handerDict = [NSDictionary dictionaryWithObjectsAndKeys:
						  m_deviceType, @"deviceType",
						  m_deviceVersion, @"deviceVersion",
						  m_deviceId, @"deviceId",
						  m_locale, @"locale",
						  m_appId, @"gameId",
						  m_appVersion, @"gameVersion", nil];
	
	NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
			commandDict, @"command",
			handerDict, @"header", nil];
	
	NSString* jsonString = [[CJSONSerializer serializer] serializeDictionary:dict];
	NSLog(@"%@", jsonString);
	
	NSMutableData *data = [[NSMutableData alloc] init];
	const char* jsonCString = [jsonString UTF8String];
	[data appendBytes:jsonCString length:strlen(jsonCString)];
    
	// create the request
	NSMutableURLRequest *post=[NSMutableURLRequest requestWithURL:[NSURL URLWithString: APP_CONNECT_URL]
														 cachePolicy:NSURLRequestUseProtocolCachePolicy
													 timeoutInterval:10.0];
	
	[post setHTTPMethod: @"PUT"];
	//[post setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[post setHTTPBody:data];
	
	// create the connection with the request
	// and start loading the data
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:post delegate:self];
	
	if (!theConnection)
		return NO;
	
	// XXX: Don't release 'theConnection' here
	// XXX: It will be released by the delegate
	
	return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse
	
    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
	
    [m_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{	
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
	[m_receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// release the connection, and the data object
    [connection release];
	
	NSLog(@"Error getting scores: %@", error);
	
	if( [m_delegate respondsToSelector:@selector(didFaileToReiciveNotification:) ] )
		[m_delegate didFaileToReceiveNotification:self];
	
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// release the connection, and the data object
    [connection release];
	
	NSString *jsonString = [[[NSString alloc] initWithBytes:[m_receivedData bytes] length:[m_receivedData length] encoding:NSUTF8StringEncoding] autorelease];
	NSLog(@"%@", jsonString);
	
	NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
	
	if(!error) {
		NSString* err = [dictionary objectForKey:@"error"];
		NSLog(@"%@", err);
		if ([err isEqual:@"0"])
		{
			NSDictionary *dict = [dictionary objectForKey:@"data"];
			if (![dict isEqual:[NSNull null]])
			{
				NSString* title = [dict objectForKey:@"title"];
				NSString* content = [dict objectForKey:@"content"];
				NSString* url = [dict objectForKey:@"url"];
				
				if( [m_delegate respondsToSelector:@selector(didReceiveNotification:WithTitle:Content:URL:) ] ) {
					[m_delegate didReceiveNotification:self WithTitle:title Content:content URL:url];
				}
			}
			
			return;
		}
	}
	
	if( [m_delegate respondsToSelector:@selector(didFaileToReiciveNotification:) ] )
		[m_delegate didFaileToReceiveNotification:self];
}

-(NSURLRequest *)connection:(NSURLConnection *)connection
			willSendRequest:(NSURLRequest *)request
           redirectResponse:(NSURLResponse *)redirectResponse
{	
    NSURLRequest *newRequest=request;
    if (redirectResponse) {
        newRequest=nil;
    }
    return newRequest;
} 

@end
